import React, { useEffect, useState } from 'react';
import ReactECharts from 'echarts-for-react';
import './index.css';
import dayjs from 'dayjs';
import { message } from 'antd';
import { getUserSignInUsingGet } from '@/api/UserApi';

interface Props {}

/**
 * 刷题记录组件
 * @param props
 * @constructor
 */
const CalendarsChart = (props: Props) => {
  const {} = props;

  // 签到日期列表[1,2]代表第一天和第二天有签到
  const [dataList, setDataList] = useState<number[]>([]);
  const year = new Date().getFullYear();

  const fetchDataList = async () => {
    try {
      const res = await getUserSignInUsingGet({
        year,
      });
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      setDataList(res.data);
    } catch (e) {
      message.error('获取签到记录失败:' + e);
    }
  };

  useEffect(() => {
    fetchDataList();
  }, []);

  // 转换echart数据
  const optionsData = dataList.map((dayOfYear) => {
    const dataStr = dayjs(`${year}-01-01`)
      .add(dayOfYear - 1, 'day')
      .format('YYYY-MM-DD');
    return [dataStr, 1];
  });
  // 图表配置
  const options = {
    visualMap: {
      show: false,
      min: 0,
      max: 1,
      inRange: {
        // 颜色从灰色到浅绿色
        color: ['#efefef', 'lightgreen'],
      },
    },
    calendar: {
      range: year,
      left: 20,
      // 单元格自动宽度，高度为 16 像素
      cellSize: ['auto', 16],
      yearLabel: {
        position: 'top',
        formatter: `${year} 年刷题记录`,
      },
    },
    series: {
      type: 'heatmap',
      coordinateSystem: 'calendar',
      data: optionsData,
    },
  };

  return <ReactECharts className="calendars-chart" option={options} />;
};

export default CalendarsChart;
